package com.deer.wms.base.system.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.deer.wms.base.system.dao.*;
import com.deer.wms.base.system.model.*;
import com.deer.wms.base.system.model.Area.AreaInfo;
import com.deer.wms.base.system.model.Area.AreaInfoCriteria;
import com.deer.wms.base.system.model.Item.*;
import com.deer.wms.base.system.model.Item.AuxProp;
import com.deer.wms.base.system.model.Supplier.SuppInfoBO;
import com.deer.wms.base.system.model.Supplier.SupplierInfo;
import com.deer.wms.base.system.model.Supplier.SupplierManage;
import com.deer.wms.base.system.service.AreaInfoService;
import com.deer.wms.base.system.service.ErpService;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.BeanUtils;
import com.deer.wms.project.root.util.HttpClient;
import com.deer.wms.system.manage.dao.DeptMapper;
import com.deer.wms.system.manage.model.customer.Customer;
import com.deer.wms.system.manage.model.dept.Dept;
import com.deer.wms.system.manage.service.CustomerService;
import com.deer.wms.system.manage.service.DeptService;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import javax.activation.DataHandler;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Service
//@Transactional
public class ErpServiceImpl extends SuperServiceImpl<ErpBackRecordMapper, ErpBackRecord> implements ErpService {

//    @Value("${lzb.erp.ip}")
//    private String erpIp;

    @Autowired
    private ErpBackRecordMapper erpBackRecordMapper;

    @Autowired
    private BillDetailMapper billDetailMapper;

    @Autowired
    private ItemInfoMapper itemInfoMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    private DeptInfoMapper deptInfoMapper;

    @Autowired
    private CustInfoMapper custInfoMapper;

    @Autowired
    private SuppInfoMapper suppInfoMapper;

    @Autowired
    private PurOrderMapper purOrderMapper;

    @Autowired
    private PurOrderDetailMapper purOrderDetailMapper;

    @Autowired
    private ItemInfoNewMapper itemInfoNewMapper;

    @Autowired
    private AuxPropMapper auxPropMapper;
    @Autowired
    private ItemInfoService itemInfoService;
    @Autowired
    private AreaInfoService areaInfoService;

    @Autowired
    private DeptService deptService;

    @Autowired

    private DeptMapper deptMapper;

    @Autowired
    private SupplierManageServiceImpl supplierManageService;

    @Autowired
    private CustomerService customerService;

    @Value("${erp.tokenUrl}")
    private String tokenUrl;


//     private static final String BASE_URL = "http://10.18.3.19:34398";  //test测试
     private  String BASE_URL = "http://10.18.3.19:34399";  //正式服务器


    @Override
    public void saveItemInfo() {

        for (int i = 0; i < 10; i++) {
//            ;
            int finalI = i;
//            CompletableFuture.runAsync(()->{
                this.saveItemInfo(finalI, 50000);
//        });
        }



    }


    public void insertItemInfo(List<ItemErpBO> list) {
        List<ItemInfo> itemInfos = new ArrayList<>();
        for (ItemErpBO bo : list) {
            ItemInfo itemInfo = new ItemInfo();
            itemInfo.setId(bo.getId());
            itemInfo.setErpItemId(bo.getId());
            itemInfo.setDefaultStockId(bo.getDefaultStockId());
            itemInfo.setDefaultStockName(bo.getDefaultStockName());
            itemInfo.setFeedCategory(bo.getFeedCategory()); //发料属性
            itemInfo.setBatchManager(bo.getBatchManager());
            itemInfo.setCategory(bo.getCategory()); //通用属性
            itemInfo.setItemCode(bo.getNumber());//物料编码
            itemInfo.setItemName(bo.getName());//物料名称
            itemInfo.setPackCode("sys_pack");
            itemInfo.setItemStatus(bo.getEnabled() == false ? "disable" : "enable");//启用
            itemInfo.setSpec(bo.getModel());//规格
            itemInfo.setModel(bo.getModel());//型号
            itemInfo.setFloorLimit(bo.getUnitId());//计量单位ID
            itemInfo.setUnitName(bo.getUnitName());//主计量单位名称
            itemInfo.setOrganizationId(-1);//物料ID
            itemInfo.setItemBarCode(bo.getErpClsName());//物料属性
            itemInfo.setItemTypeId(bo.getAuxPropClassId());//物料辅助属性类别ID
//         //批次管理
            itemInfo.setMemo(bo.getBatchManager() == false || bo.getBatchManager() == null ? "0" : "1");
            itemInfo.setWeight(bo.getQuality());//材质
            itemInfo.setBatchTacticCode(bo.getShelfLifeDays().toString());
            itemInfos.add(itemInfo);
        }
        if (ObjectUtil.isNotEmpty(itemInfos)) {
            itemInfoService.saveOrUpdateBatch(itemInfos);
        }
    }

    public void saveItemInfo(int startPage, int end ) {

        try {
            String token = getToken();
            Map<String, Integer> map1 = new HashMap<>();
            map1.put("currentPage", startPage);
            map1.put("pageSize", end);
            try {
                //调用erp接口获取数据
                CloseableHttpClient client = HttpClients.createDefault();
                URIBuilder uriBuilder = new URIBuilder(BASE_URL+"/api/ICItem/GetRangeICItems");
                HttpPost post = new HttpPost(uriBuilder.build());
                StringEntity myEntity = new StringEntity(JSON.toJSONString(map1), "UTF-8");// 构造请求数据
                post.setHeader("Content-Type", "application/json");
                post.addHeader("Authorization", "Bearer " + token);
                post.setEntity(myEntity);// 设置请求体
                String responseContent = null; // 响应内容
                CloseableHttpResponse response = null;
                response = client.execute(post);
                HttpEntity entity = response.getEntity();
                if (response.getStatusLine().getStatusCode() == 200) {
                    String content = EntityUtils.toString(entity, "UTF-8");
                    ItemResponseBO itemResponseBO = JSONArray.parseObject(content, ItemResponseBO.class);
                    String it = itemResponseBO.getList();
                    List<ItemErpBO> itemErpBOS = (List<ItemErpBO>) JSON
                            .parseArray(it, ItemErpBO.class);
                    this.insertItemInfo(itemErpBOS);
                }

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

        }

        catch (Exception e) {
            e.printStackTrace();
        }

    }




    @Override
    public String saveWarehouseInfo() {

        try {
            String token = getToken();
            if( token!= null){
                //调用erp接口获取数据
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.add("Accept", "application/json");
                httpHeaders.add("Authorization", "Bearer " + token);
                String url = BASE_URL+"/api/Stock/GetAllStocks";
                String result = HttpClient.getRequest(url, null, httpHeaders);
                JSONArray jsonArray = JSONArray.parseArray(result);
                List<WarehouseBO> ws = JSONObject.parseArray(jsonArray.toJSONString(), WarehouseBO.class);
                List<AreaInfo> areaInfoList = new ArrayList<>();
                this.saveBatch(ws);

            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void saveBatch(List<WarehouseBO> list) {
        List<AreaInfo> areaInfoList = new ArrayList<>();
        Set<Integer> collect = list.stream().map(WarehouseBO::getId).collect(Collectors.toSet());
        Set<Integer> areaCode = areaInfoService.list(new QueryWrapper<AreaInfo>().in("erp_area_id", collect)).stream().map(AreaInfo::getErpAreaId).collect(Collectors.toSet());
        for (WarehouseBO item : list) {
            if (areaCode.contains(item.getId())) {
                continue;
            }
            AreaInfo areaInfo = new AreaInfo();
            areaInfo.setAreaCode(item.getNumber());
            areaInfo.setAreaName(item.getName());
            areaInfo.setWareId(285);
            areaInfo.setErpAreaId(item.getId());
            areaInfoList.add(areaInfo);
        }

        areaInfoService.saveBatch(areaInfoList);

    }
    @Override
    public String saveDeptInfo() {
        try {
            String token = getToken();
            if(token != null){
                //调用erp接口获取数据
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.add("Accept", "application/json");
                httpHeaders.add("Authorization", "Bearer " + token);
                String url = BASE_URL+"/api/dept/getalldepts";
                String result = HttpClient.getRequest(url, null, httpHeaders);
                JSONArray jsonArray = JSONArray.parseArray(result);
                List<DeptInfoBO> di = JSONObject.parseArray(jsonArray.toJSONString(), DeptInfoBO.class);
                deptMapper.deleteDept();
                List<Dept> list = new ArrayList<>();
                if(di.size() != 0){
                    for(DeptInfoBO bo : di){
                            Dept dept = new Dept();
                            dept.setDeptCode(bo.getNumber());
                            dept.setDeptName(bo.getName());
                            dept.setDeptId(bo.getId());
                            dept.setEnabled(bo.getEnabled());
                            list.add(dept);
                    }
                    deptService.saveBatch(list);
                }
            }
            return null;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String saveCustomerInfo() {

        try {
            String token = getToken();
            if(token != null){
                //调用erp接口获取数据
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.add("Accept", "application/json");
                httpHeaders.add("Authorization", "Bearer " + token);
                String url = BASE_URL+"/api/Customer/GetAllCustomers";
                String result = HttpClient.getRequest(url, null, httpHeaders);
                JSONArray jsonArray = JSONArray.parseArray(result);
                List<CustInfoBO> ci = JSONObject.parseArray(jsonArray.toJSONString(), CustInfoBO.class);
                List<Customer> list = new ArrayList<>();
                if(ci.size() != 0){
                    for(CustInfoBO bo : ci){
//                        //先判断抓取的数据在数据库中是否存在
//                        QueryWrapper<Customer> qw = Wrappers.query();
//                        Customer customer = customerService.getOne(qw.eq("cus_num", bo.getNumber()));
//                        if(info == null){
                            Customer customer = new Customer();
                        customer.setCustomerCode(bo.getNumber());
                        customer.setCustomerId(bo.getId());
                        customer.setCustomerName(bo.getName());
                        list.add(customer);
//                        }
                    }
                    customerService.saveOrUpdateBatch(list);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return null;
    }

    @Override
    public String saveSupplierInfo() {

        try {
            String token = getToken();
            if(token != null){
                //调用erp接口获取数据
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.add("Accept", "application/json");
                httpHeaders.add("Authorization", "Bearer " + token);
                String url = BASE_URL+"/api/Supplier/GetAllSuppliers";
                String result = HttpClient.getRequest(url, null, httpHeaders);
                JSONArray jsonArray = JSONArray.parseArray(result);
                List<SuppInfoBO> si = JSONObject.parseArray(jsonArray.toJSONString(), SuppInfoBO.class);
                supplierManageService.clear();
                List<SupplierManage> supplierManages = new ArrayList<>();
                if(si.size() != 0){
                    for(SuppInfoBO bo : si){
                        SupplierManage supplierManage = new SupplierManage();
                        supplierManage.setSupplierCode(bo.getNumber());
                        supplierManage.setSupplierId(bo.getId());
                        supplierManage.setSupplierName(bo.getName());
                        supplierManage.setEnabled(bo.getEnabled());
                        supplierManages.add(supplierManage);
                    }
                    supplierManageService.saveBatch(supplierManages);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return null;
    }

    @Override
    public String savePurchaseOrder() {

        try {
            String token = getToken();

            if(token != null){
                //调用erp接口获取数据
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.add("Accept", "application/json");
                httpHeaders.add("Authorization", "Bearer " + token);
                String url = BASE_URL+"/api/Epichust/GetAllIMInSourceBills";
                String result = HttpClient.getRequest(url, null, httpHeaders);
                System.out.println("result" + result);
                JSONArray jsonArray = JSONArray.parseArray(result);
                List<PurchaseOrderBO> po = JSONObject.parseArray(jsonArray.toJSONString(), PurchaseOrderBO.class);

                if(po.size() != 0){
                    for(PurchaseOrderBO bo : po){
                        //先判断抓取的数据在数据库中是否存在
                        QueryWrapper<PurchaseOrder> qw = Wrappers.query();
                        Map<String, Object> map = new HashMap<>();
                        map.put("bill_no", bo.getBillNo());
                        map.put("bill_type_id", bo.getBillTypeId());
                        PurchaseOrder info = purOrderMapper.selectOne(qw.allEq(map, false));

                        if(info == null){
                            PurchaseOrder purchaseOrder = new PurchaseOrder();
                            purchaseOrder.setOrderId(bo.getId());
                            purchaseOrder.setBillTypeId(bo.getBillTypeId());
                            purchaseOrder.setBillTypeName(bo.getBillTypeName());
                            purchaseOrder.setBillNo(bo.getBillNo());
//                            purchaseOrder.setBillDate(bo.getBillDate());
                            purchaseOrder.setBillStatus(bo.getBillStatus());
                            purchaseOrder.setBillClosed(bo.getBillClosed());
                            purchaseOrder.setSupplierId(bo.getSupplierId());
                            purchaseOrder.setSupplierName(bo.getSupplierName());
                            purchaseOrder.setCustomerId(bo.getCustomerId());
                            purchaseOrder.setCustomerName(bo.getCustomerName());
                            purchaseOrder.setDeptId(bo.getDeptId());
                            purchaseOrder.setDeptName(bo.getDeptName());
                            purchaseOrder.setRemark(bo.getRemark());
                            purOrderMapper.insert(purchaseOrder);
                            System.out.println("保存了主表信息");
                            List<PurchaseOrderDetailBO> purchaseOrderDetailBOS = bo.getDetails();
                            for(PurchaseOrderDetailBO purchaseOrderDetailBO :purchaseOrderDetailBOS){
                                PurOrderDetail purOrderDetail = new PurOrderDetail();
                                purOrderDetail.setPurId(purchaseOrder.getId());
                                purOrderDetail.setRowIndex(purchaseOrderDetailBO.getRowIndex());
                                purOrderDetail.setItemId(purchaseOrderDetailBO.getItemId());
                                purOrderDetail.setItemNumber(purchaseOrderDetailBO.getItemNumber());
                                purOrderDetail.setItemName(purchaseOrderDetailBO.getItemName());
                                purOrderDetail.setItemModel(purchaseOrderDetailBO.getItemModel());
                                purOrderDetail.setAuxPropClassId(purchaseOrderDetailBO.getAuxPropClassId());
                                purOrderDetail.setAuxPropId(purchaseOrderDetailBO.getAuxPropId());
                                purOrderDetail.setAuxPropName(purchaseOrderDetailBO.getAuxPropName());
//                                purOrderDetail.setAuxUnitId(purchaseOrderDetailBO.getAuxUnitId());
//                                purOrderDetail.setAuxUnitName(purchaseOrderDetailBO.getAuxUnitName());
                                purOrderDetail.setBatchManager(purchaseOrderDetailBO.getBatchManager());
                                purOrderDetail.setBatchNo(purchaseOrderDetailBO.getBatchNo());
//                                purOrderDetail.setAuxQty(purchaseOrderDetailBO.getAuxQty());
//                                purOrderDetail.setAuxCommitQty(purchaseOrderDetailBO.getAuxCommitQty());
                                purOrderDetail.setUnitId(purchaseOrderDetailBO.getUnitId());
                                purOrderDetail.setQty(purchaseOrderDetailBO.getQty());
//                                purOrderDetail.setCommitQty(purchaseOrderDetailBO.getCommitQty());
//                                purOrderDetail.setPlanModeId(purchaseOrderDetailBO.getPlanModeId());
                                purOrderDetail.setMtoNo(purchaseOrderDetailBO.getMtoNo());
                                purOrderDetail.setRemark(purchaseOrderDetailBO.getRemark());
                                purOrderDetail.setTargetBillTypeId(purchaseOrderDetailBO.getTargetBillTypeId());
                                purOrderDetail.setTargetBillRob(purchaseOrderDetailBO.getTargetBillROB());
                                purOrderDetailMapper.insert(purOrderDetail);
                                System.out.println("保存了子表信息");
                            }
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return null;
    }



    @Override
    public String saveAuxProps() {

        try {
            String token = getToken();
            if(token != null){

//                for(int i = 1 ; i<=8; i++){
                    Map<String, Integer> map1 = new HashMap<>();
                    map1.put("currentPage",1);
                    map1.put("pageSize",10000);

                    //调用erp接口获取数据
                    CloseableHttpClient client = HttpClients.createDefault();
                    URIBuilder uriBuilder = new URIBuilder(BASE_URL+"/api/AuxProp/GetRangeAuxProps/3033");
                    HttpPost post = new HttpPost(uriBuilder.build());
                    StringEntity myEntity = new StringEntity(JSON.toJSONString(map1), "UTF-8");// 构造请求数据
                    post.setHeader("Content-Type", "application/json");
                    post.addHeader("Authorization", "Bearer " + token);
                    post.setEntity(myEntity);// 设置请求体
                    String responseContent = null; // 响应内容
                    CloseableHttpResponse response = null;
                    try {
                        response = client.execute(post);
                        HttpEntity entity = response.getEntity();
                        if (response.getStatusLine().getStatusCode() == 200) {
                            String content = EntityUtils.toString(entity, "UTF-8");
                            ItemResponseBO itemResponseBO = JSONArray.parseObject(content, ItemResponseBO.class);
                            String it = itemResponseBO.getList();
                            List<AuxPropBO> auxPropBOS = (List<AuxPropBO>) JSON
                                    .parseArray(it, AuxPropBO.class);
                            if(auxPropBOS.size() != 0){
                                for(AuxPropBO bo : auxPropBOS){
                                    AuxProp auxProp = new AuxProp();
                                    auxProp.setAuxId(bo.getId());
                                    auxProp.setAuxName(bo.getName());
                                    auxProp.setAuxNumber(bo.getNumber());
                                    auxProp.setUsed(bo.getEnabled());
                                    auxProp.setAuxTypeId(3033);
                                    auxPropMapper.insert(auxProp);

                                }

                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }  finally {
                        try {
                            if (response != null)
                                response.close();

                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                if (client != null)
                                    client.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
            }

            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    //异步执行
    @Async
    public void saveErpBack(ErpBackRecord erpBackRecord) {
        this.save(erpBackRecord);
    }

    /**
     * 查询ERP回传日志
     * @param criteria
     * @return
     */
    @Override
    public List<ErpBackRecord> findList(ErpRecordCriteria criteria) {
        return erpBackRecordMapper.selectList(criteria);
    }


    @Value("${erp.ClientID}")
    private String clientID;
    @Value("${erp.ClientSecret}")
    private String ClientSecret;


    public String getToken() {
//        //请求token
        MultiValueMap<String, String> stringMultiValueMap = new LinkedMultiValueMap<>();

        stringMultiValueMap.add("client_id", this.clientID);
        stringMultiValueMap.add("client_secret", this.ClientSecret);
        stringMultiValueMap.add("grant_type", "password");
        stringMultiValueMap.add("username", "epichust");
        stringMultiValueMap.add("password", "hK@vmz0YI1e^thtB");
        String tokenUrl = this.tokenUrl+"/connect/token";
        System.out.println(tokenUrl);
        System.out.println(this.clientID);
        System.out.println(this.ClientSecret);
        String clientRg = null;
        try {
            clientRg = HttpClient.clientRg(tokenUrl, HttpMethod.POST, stringMultiValueMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(clientRg);
        return jsonObject.getString("access_token");
        //过期时间
//        String pasts = jsonObject.getString("expires_in");
    }

}
